package com.example.jpatest.service.impl;

import com.example.jpatest.entity.Enter;
import com.example.jpatest.entity.Student;
import com.example.jpatest.entity.Team;
import com.example.jpatest.repository.StudentRepository;
import com.example.jpatest.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author czx
 */
@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    StudentRepository studentRepository;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public Student saveStudent(Student student) {
        return studentRepository.save(student);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void joinTeam(Student student,Team team) {
        student.addTeam(team);
        studentRepository.save(student);
    }

    @Override
    public Student getByStudentNumber(String studentNumber) {
        return studentRepository.findByStudentNumber(studentNumber).orElse(null);
    }

    @Override
    public Set<Team> getAllTeams(Student student) {
        return student.getTeams();
    }

    @Override
    public List<Student> getStudents() {
        return studentRepository.findAll();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteByStudentNumber(String StudentNumber) {
        studentRepository.deleteByStudentNumber(StudentNumber);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void quitTeam(Student student, Team team) {
        if (student.getTeams().contains(team)) {
            student.getTeams().remove(team);
        }
    }

    @Override
    public List<Enter> getEnters(Student student) {
        List<Enter> enters = new LinkedList<>();
        for (Team team : student.getTeams()) {
            enters.addAll(team.getEnter());
        }
        return enters;
    }

    @Override
    public boolean isInTeam(Student student, Team team) {
        return student.getTeams().contains(team);
    }
}
